using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace imitateMacQQ.WebApi.Domain.Token.wand.utils;

public class JwtHelper
{
    private readonly IConfiguration _configuration;

    public JwtHelper(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    /// <summary>
    /// 获取token
    /// </summary>
    /// <param name="account">要获取token的账户</param>
    /// <param name="time">token验证时常 min</param>
    /// <returns></returns>
    public string CreateToken(string account,double time = 30)
    {
        if (account == "COMEBACK")
            return "";
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, "u_admin"),
            new Claim(ClaimTypes.Role, "r_admin"),
            new Claim(JwtRegisteredClaimNames.Jti, "admin"),
            new Claim("Username", account),
        };
        var s = _configuration["Jwt:SecretKey"];
        if(s is null)
            return "";
        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(s));
        var algorithm = SecurityAlgorithms.HmacSha256;
        var signingCredentials = new SigningCredentials(secretKey, algorithm);
        var jwtSecurityToken = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],    
            _configuration["Jwt:Audience"],   
            claims,                         
            DateTime.Now,                   
            DateTime.Now.AddMinutes(time),   
            signingCredentials               
        );
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return token;
    }
}